package com.lsp.server.user.service;

import com.lsp.server.common.Apiresponse;
import com.lsp.server.user.domain.po.UserEntity;
import com.lsp.server.user.mapper.UserMapper;
import com.lsp.server.utils.JWT;
import com.lsp.server.utils.Md5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserService
 * @Description 用户管理业务层
 * @Author Mr Hao
 * @Date 2021/11/14 18:17
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     *处理用户列表数据
     * @return
     */
    public Object getUser() {

        List<UserEntity> list = userMapper.getUser();
        if (null == list){
           return null;
        }

        return list;
    }

    /**
     * 添加新用户
     * @param user
     * @return
     */
    public void addUser(UserEntity user) {

        user.setCreateDate(new Date());
        userMapper.addUser(user);
    }

    /**
     * 登录
     * @param name
     * @param password
     * @return
     */
    public Map login(String name, String password) {
        Map rs = new HashMap();
        UserEntity user = userMapper.login(name);
        if (user.getName() == null) {
            rs.put("code", 3);
        } else if (!user.getPassword().equals(password)) {
            rs.put("code", 2);
        }else {
            String sign = JWT.sign(name, 60 * 60 * 24);
            rs.put("code", 1);
            rs.put("token", sign);
        }
        return rs;
    }
    /**
     * 修改用户
     * @param form
     */
    public void upateUesr(UserEntity form) {
        userMapper.upateUesr(form);
    }

    /**
     * 回显
     * @param id
     * @return
     */
    public Object findUserById(String id) {
        UserEntity userEntity = userMapper.findUserById(id);
        //判读userEntity是否为空
        if (null == userEntity){
            return "";
        }
        //向前台返回数据
        return userEntity;
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    public void delUserById(String ids) {
        userMapper.delUserById(ids);
    }

    /**
     * 注册账号
     * @param request
     * @param name
     * @param password
     */
    public void updatePass(HttpServletRequest request, String name, String password) {
        UserEntity user = new UserEntity();

        String md5ps = Md5.LycMD5(Md5.LycMD5(password) + name);

        user.setPassword(md5ps);

        // 设置新密码进去
        userMapper.updateUserPassByUserEmail(user);
    }

    public Object userExistsByName(String name) {
        UserEntity userEntity = userMapper.userExistsByName(name);

        //判断账号是否存在（1否 0是）
        if (userEntity == null){
            return 1;
        }
        return 0;
    }
}
